#include "widget.h"
#include "ui_widget.h"
#include <QPushButton>
#include <QVBoxLayout>
#include <QFrame>
#include <QPainter>
#include <QSpacerItem>
#include <QDebug>

static const int window_frame = 5;
static const int window_width = 960;
static const int window_height = 640;
static const int block_size = 20;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);

    // 允许窗口接受鼠标事件（用于拖动和点击）
    setAttribute(Qt::WA_TranslucentBackground);
    setAttribute(Qt::WA_NoSystemBackground, false);

    // 设置窗口大小
    this->setFixedSize(QSize(window_width + window_frame * 2, window_height + window_frame * 2));

    // 场景管理器
    stackedWidget = new QStackedWidget(this);

    startSence = new StartSence(this, window_frame, window_width, window_height);
    startSence->setFixedSize(this->size());
    connect(startSence, &StartSence::exit, this, &QWidget::close);
    connect(startSence, &StartSence::play, this, &Widget::playGame);

    playGameSence = new PlayGameSence(this, window_frame, window_width, window_height, block_size);
    playGameSence->setFixedSize(this->size());
    connect(playGameSence, &PlayGameSence::exitGame, this, &Widget::exitGameHandle);

    stackedWidget->addWidget(startSence);
    stackedWidget->addWidget(playGameSence);

    stackedWidget->setCurrentIndex(0);

    // 添加布局管理
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(stackedWidget);
    mainLayout->setContentsMargins(0, 0, 0, 0);  // 设置边距为0，填满整个窗口
}


void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
         dragPosition = event->globalPos() - frameGeometry().topLeft();
         event->accept();
    }
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton)
    {
        move(event->globalPos() - dragPosition);
        event->accept();
    }
}

void Widget::paintEvent(QPaintEvent *event)
{
    (void)event;
    QPainter painter(this);

    // 绘制边框
    QPen pen;
    pen.setColor(QColor(0, 0, 0));
    pen.setWidth(window_frame * 2);
    painter.setPen(pen);
    painter.drawRect(0, 0, window_width + window_frame, window_height + window_frame);
}

void Widget::playGame()
{
    playGameSence->setPlayerNum(1);
    stackedWidget->setCurrentIndex(1);
}

void Widget::exitGameHandle()
{
    stackedWidget->setCurrentIndex(0);
}


Widget::~Widget()
{
    delete ui;
}

